package cc.catface.api.global;

import cc.catface.api.global.interceptor.LogInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired/*添加拦截器及拦截策略==>*/
    private LogInterceptor logInterceptor;

    private final String[] ADD_PATH = {//拦截器拦截策略
            "/**"
    };
    private final String[] EXCLUDE_PATH = {//拦截器不拦截策略
            "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**"//swagger
    };

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(logInterceptor).addPathPatterns(ADD_PATH)
                .excludePathPatterns(EXCLUDE_PATH);
    }//<==

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //静态资源
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        //swagger
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }


    @Override/*跨域*/
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")//允许任何域名使用
                .allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH")//允许任何请求方法
                .allowedHeaders("*")//允许任何请求头
                //.allowCredentials(true)//cookie
                .maxAge(3600L);//3600秒内不需要再发送预检验请求,可以缓存该结果
    }
}
